#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "pthread.h"
#include <signal.h>


pthread_mutex_t lock;   
pthread_mutex_t lock1; 
pthread_cond_t equal;  
pthread_cond_t equal1; 
static int i=7,j=6;

void *thread1(void *data)
{     
      int x;
      int lood;

     
      while(j>=0){
      pthread_mutex_lock(&lock);
         if (j == 0) {
         printf("qqqqqqqqqqqqqq");
	   pthread_cond_signal(&equal);
           printf("RIGHT passed! LEFT pass\n");	
           }
          if(i>0)
          {
          x=j;
         //pthread_cond_signal(&equal);
          printf("hahahah");
           pthread_cond_wait(&equal1,&lock);
     
	   }
	   sleep(1);
	   if(x-1!=j){
	   pthread_cond_signal(&equal);
	   }
	   			
        
           if (j >0) 
           
           j--;
           sleep(1);
	   printf("R: LEFT=%d,RIGHT=%d\n",i,j);
           pthread_mutex_unlock(&lock);
           }
      
        return NULL;
}

void *thread2(void *data)
{       int x;
        	
	while(i>=0){
	pthread_mutex_lock(&lock);
        if (i == 0) {
            
            printf("LEFT passed! RIGHT pass\n");
            pthread_cond_signal(&equal1);
         
            pthread_mutex_unlock(&lock);
            pthread_cond_wait(&equal,&lock);

        }
       
      	if(i>0)
            i--;
            sleep(1);
	    printf("L: LEFT=%d,RIGHT=%d\n",i,j);
            pthread_mutex_unlock(&lock);
	} 
	



}
void *thread3(void *data)
{
        int a,b;
        a=1;
            while(1){	
        pthread_mutex_lock(&lock);
        pthread_mutex_unlock(&lock);  
     
        a= rand()%10;
        b= rand()%10;
        sleep(10);
        i=i+a;
        j=j+b;
         
        
        }
      
}

int main(int argc,char *argv[])
{
	pthread_t th_left;
	pthread_t th_right;
	pthread_t th_a;
	
	void * retval;
	int loop;
	

        
	pthread_mutex_init(&lock,NULL);
	pthread_mutex_init(&lock1,NULL);
	pthread_cond_init(&equal,NULL);	
	pthread_cond_init(&equal1,NULL);
	pthread_create(&th_left, NULL, thread1, 0);
	pthread_create(&th_right, NULL, thread2, 0);
	pthread_create(&th_a, NULL, thread3, 0);	

          
       
       pthread_join(th_left, &retval);
       pthread_join(th_right, &retval);
       pthread_mutex_destroy(&lock);
       pthread_cond_destroy(&equal);
 
       return 0;
}


